package com.example.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.example.common.core.constants.Constants;
import com.example.common.core.constants.HttpConstants;
import com.example.common.core.constants.TTLConstants;
import com.example.common.security.service.TokenService;
import com.example.common.security.utils.ThreadLocalUtil;
import com.example.redis.service.RedisService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;//从哪个服务中的配置文件中读取，取决于

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = getTokenFromRequest(request);
        //令牌为空也放行，因为拦截器不是为了检验登陆，只是为了延长令牌时间
        if (StrUtil.isEmpty(token)) {
            return true;
        }
        Claims claims = tokenService.getClaims(token,secret);
        tokenService.extendToken(claims);
        //把userId保存一下
        Long userId = tokenService.getUserId(claims);
        //把userKey也保存一下
        String userKey = tokenService.getUserKey(claims);
        ThreadLocalUtil.set(TTLConstants.USER_ID, userId);
        ThreadLocalUtil.set(TTLConstants.USER_KEY, userKey);
        return true;
    }

    //从request中获取token
    public String getTokenFromRequest(HttpServletRequest request){
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)){
            token = token.replaceFirst(HttpConstants.PREFIX,"");
        }
        return token;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }


    //执行完controller之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理掉之前保存的变量
        ThreadLocalUtil.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
